package com.finapps.stopspend.dao;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.finapps.stopspend.entidades.Carrec;
import com.finapps.stopspend.entidades.ObjetivoEntity;

public class CarrecsDAO {	
	private static final String[] PLACE_COLUMNS={"id","data","hora","descripcio","carrec","saldo","estalvi_mes"};
	private static final String NAMETABLE = "Transactions";


	/**
	 * 
	 * @param dataInici En format AAAAMMDD
	 * @param dataFi En format AAAAMMDD
	 * @return
	 */
	public List<Carrec> getAllCarrecs(String dataInici,String dataFi) {
		List<Carrec> list = new ArrayList<Carrec>();
		Cursor cursor = null;
		Database database = Database.get();
		SQLiteDatabase db = database.open();
		cursor = db.query(NAMETABLE, PLACE_COLUMNS, null, null, null, null, null);
		if(cursor.moveToFirst()) {
			do {
				Carrec carrec = getCarrec(cursor);
				list.add( carrec );
			} while(cursor.moveToNext());
		}
		cursor.close();
		database.close();
		return list;
	}
	
	/*
	 * Retorna c�rrec m�s proper a data i hora pero mai superant-la (Si hi ha c�rrecer per la data i hora
	 * el retorna sino retorna el m�s proper anterior
	 * @param data En format AAAAMMDD
	 */
	public Carrec getCarrecMesProper(String data,String hora) {
		Carrec carrec = null;
		Cursor cursor1 = null;
		Database database = Database.get();
		SQLiteDatabase db = database.open();
		cursor1 = db.query(NAMETABLE, PLACE_COLUMNS, "data<? or ( data=? AND hora<=?)", new String[]{data,hora}, null, null, null);
		if(cursor1.moveToLast()) {
				carrec = getCarrec(cursor1);
		}
		cursor1.close();
		database.close();
		return carrec;
		
	}
	
	/**
	 * 
	 * @param data data En format AAAAMMDD
	 */
	public Carrec getUltimCarrecData(String data) {
		Carrec objectivo = null;
		Cursor cursor = null;
		Database database = Database.get();
		SQLiteDatabase db = database.open();
		cursor = db.query(NAMETABLE, PLACE_COLUMNS, "data=?", new String[]{data}, null, null, null);
		if(cursor.moveToLast()) {
				objectivo = getCarrec(cursor);
		}
		cursor.close();
		database.close();
		return objectivo;
	}
	
	private Carrec getCarrec(Cursor cursor){
		Carrec carrec = null;
		BigDecimal cost = new BigDecimal(cursor.getDouble(4));
		BigDecimal falta = new BigDecimal(cursor.getDouble(5));
		BigDecimal acumulat = new BigDecimal(cursor.getDouble(6)); // Posar valor real
		carrec = new Carrec(cursor.getLong(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
				cost,falta,acumulat);
		return carrec;
	}
	
}
